<template>
  <div class="address-func">
    <div class="block">
      <header>
        <h2 class="required">
          <slot name="title" />
        </h2>
        <el-divider direction="vertical" />
        <el-link type="primary" @click="openAddressAddDialog()">
          <slot name="btn-name">新增收货地址</slot>
        </el-link>
      </header>
      <section>
        <el-radio-group
          v-model="address"
          class="w100p address-group"
          @change="onChangeAddress"
        >
          <el-row v-for="item in rows_address" :key="item.id">
            <el-col
              class="address-item"
              :class="{ highline: item.id === address }"
            >
              <el-radio-button :label="item.id" class="title">
                <div class="name">
                  {{ item.userName }}
                </div>
              </el-radio-button>
              <el-divider direction="vertical" />
              <span class="detail">{{ item.userName }}</span>
              <el-divider v-if="infoType === 'full'" direction="vertical" />
              <span v-if="infoType === 'full'" class="detail">
                <span>{{ item.province }} {{ item.city }} {{ item.area }}</span>
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="item.detailedAddress"
                  placement="top-start"
                >
                  <span class="overflow-text">{{ item.detailedAddress }}</span>
                </el-tooltip>
              </span>
              <el-divider direction="vertical" />
              <span class="detail">{{ item.userPhone }}</span>
              <el-button
                v-if="item.id === address"
                size="small"
                type="text text-primary"
                style="margin-left:10px;"
                @click="openAddressAddDialog(item)"
                >编辑</el-button
              >
              <el-button
                v-if="item.id === address"
                size="small"
                type="text text-primary"
                style="color: red;"
                @click="deleteAddress(item.id)"
                >删除</el-button
              >
            </el-col>
          </el-row>
          <div v-if="showMoreAddress" class="more">
            <el-button
              v-if="toggleMoreAddress === false"
              type="text"
              @click="onClickMoreAddress"
            >
              {{ moreBtnText }}
              <i class="el-icon-arrow-down" />
            </el-button>
            <el-button v-else type="text" @click="onClickLessAddress">
              收起
              <i class="el-icon-arrow-up" />
            </el-button>
          </div>
        </el-radio-group>
      </section>
    </div>
  </div>
</template>
<script>
import { getOrderAddressList, deleteOrderAddress } from '@api/m_mall_web_v1.js';
// eslint-disable-next-line import/named
import { AddressAddDialogService } from './address-dialog/address-add.dialog.module';

export default {
  name: 'AddressFunc',
  props: {
    addressId: {
      default: '',
      type: String
    },
    // 目前只有两个值，默认全部显示（full），less是指地址信息缩量展示
    infoType: {
      default: 'full',
      type: String
    },
    moreBtnText: {
      default: '更多地址',
      type: String
    },
    isEdit: {
      default: false,
      type: Boolean
    }
  },
  data() {
    return {
      rows_address_full: [],
      rows_address: [],
      itemAddress: {},
      address: this.addressId,
      toggleMoreAddress: false,
      showMoreAddress: false,
      showAddress: true
    };
  },
  computed: {
    addressAddDialogService() {
      return new AddressAddDialogService(this.$axios);
    }
  },
  watch: {
    addressId: {
      handler(val) {
        this.address = val;
        const address = this.rows_address.find(item => item.id === val);
        this.$emit('change-address', address);
      },
      immediate: true
    }
  },
  created() {
    this.reloadAddress();
  },
  methods: {
    onChangeAddress(value) {
      this.$emit('update:addressId', value);
      const address = this.rows_address.find(item => item.id === value);
      this.$emit('change-address', address);
    },
    onClickMoreAddress() {
      this.rows_address = this.rows_address_full;
      this.toggleMoreAddress = true;
    },
    onClickLessAddress() {
      this.rows_address = this.rows_address_full.slice(0, 2);
      this.toggleMoreAddress = false;
    },
    // 删除地址
    deleteAddress(id) {
      this.$confirm('是否要删除此收货地址？', '删除收货地址', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const params = {
            id
          };
          this.$axios.$post(deleteOrderAddress, params).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.toggleMoreAddress = false;
            this.reloadAddress();
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    openAddressAddDialog(item) {
      if (item) {
        if (item.id) {
          this.itemAddress = item;
          this.addressAddDialogService
            .create({
              title: '新增收货地址',
              data: this.itemAddress,
              query: {},
              confirmButtonClickHandler: (data = {}) => {
                // 刷新完后，默认选中刚新增的记录上
                this.toggleMoreAddress = false;
                if (data) {
                  this.reloadAddress();
                }
              }
            })
            .mount();
        }
      } else {
        this.addressAddDialogService
          .create({
            title: '新增收货地址',
            query: {},
            confirmButtonClickHandler: (data = {}) => {
              // 刷新完后，默认选中刚新增的记录上
              this.toggleMoreAddress = false;
              if (data) {
                this.reloadAddress();
              }
            }
          })
          .mount();
      }
    },
    reloadAddress() {
      this.$axios({
        method: 'post',
        url: getOrderAddressList
      }).then(res => {
        if (!res.data.code) return;
        this.rows_address_full = res.data.payload || [];
        // 存在地址列表
        if (this.rows_address_full.length) {
          // 且非编辑模式，那么就默认选中第一个
          if (!this.isEdit) {
            const address = this.rows_address_full[0];
            this.$emit('change-address', address);
            this.address = address.id;
            this.$emit('update:addressId', this.address);
          } else {
            this.$emit('update:addressId', this.address);
            const address = this.rows_address_full.find(
              item => item.id === this.address
            );
            this.$emit('change-address', address);
          }
        } else {
          this.address = '';
          this.$emit('change-address', this.address);
          this.address = '';
          this.$emit('update:addressId', this.address);
        }
        // if (this.isEdit === false) {
        //   this.rows_address = this.rows_address_full.slice(0, 2);
        // } else {
        //   this.rows_address = this.rows_address_full;
        // }
        this.rows_address = this.rows_address_full.slice(0, 2);
        this.showMoreAddress =
          this.rows_address_full.length > this.rows_address.length;
      });
    }
  }
};
</script>
<style lang="less">
.address-func {
  .address-group {
    font-size: inherit;
    .address-item {
      margin-bottom: 10px;
      .title .el-radio-button__inner {
        width: 120px;
        .name {
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
    }
    .title {
      padding: initial;
    }
    .more {
      width: 120px;
      text-align: center;
    }
  }
  .highline {
    color: #2371c5;
    font-weight: bold;
  }
  .overflow-text {
    display: inline-block;
    width: 24%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: -2px;
  }
}
</style>
